package com.iap.admin.view.favorite.code
{
	import com.iap.common.signal.FavoriteRequestSignal;
	import com.iap.admin.view.code.EditViewCode;
	import com.iap.admin.view.favorite.FavoriteEditView;
	import com.iap.app.util.FormUtils;
	import com.iap.common.model.Favorite;
	import com.iap.common.model.Sample;
	import com.iap.common.model.VectorModel;
	
	import flash.events.Event;
	
	import spark.events.IndexChangeEvent;
	
	public class FavoriteEditViewCode extends EditViewCode
	{
		public static const CANCEL_NAME:String = "FavoriteEdit.Cancel";
		public static const SAVE_NAME:String = "FavoriteEdit.Save";
		public static const DELETE_NAME:String = "FavoriteEdit.Delete";
		
		public var onSubmit:FavoriteRequestSignal = new FavoriteRequestSignal();
		
		private var view:FavoriteEditView;
		public var canCloseForm:Boolean = false;

		private function get favoriteModel():Favorite
		{
			return model as Favorite;
		}
		private function set favoriteModel(model:Favorite):void
		{
			this.model = model;
		}

		public function FavoriteEditViewCode()
		{
			super();
		}
		
		protected function initView(view:FavoriteEditView):void
		{
			this.view = view;
			addListener();
			initValidators();
			resetFocus();
			onReady.dispatch("ready");
		}
		
		private function initValidators():void
		{
		}
		
		private function addListener():void
		{
		}
		
		private function removeListener():void
		{
		}
		
		private function resetFocus():void
		{
		}
		
		private function save(evt:Event = null):void
		{
			if(formIsValid)
				submit();
		}
		
		protected function submit(closeForm:Boolean = false):void 
		{
			canCloseForm = closeForm;
			model ||= new Favorite();
			model = FormUtils.fillObjectFromControls(view, model, FORM_PREFIX);
			onSubmit.dispatch(model, FavoriteRequestSignal.SAVE);
		}
		
		protected function remove():void 
		{
			onSubmit.dispatch(model, FavoriteRequestSignal.DELETE);
		}
		
		override public function fill(model:Object):void
		{
			super.fill(model);
		}

		protected function sampleForm_changeHandler(evt:IndexChangeEvent):void
		{
			var item:Sample = view.sampleSelectForm.dataProvider[evt.newIndex] as Sample;
			setSample(item);
		}

		private function setSample(sample:Sample):void
		{
			if(model == null) return;
			favoriteModel.sample = sample;
			updateVisorFromModel();
		}

		public function updateVisorFromModel():void
		{
			var item:Sample = favoriteModel.sample;
			view.sampleForm.setSource(item.vectorModel.vectorImages, item.sampleFillers);
		}
	}
}